package com.alibaba.cloud.interfaces.web;

import com.alibaba.cloud.application.banktransfer.CreateBankTransferCommand;
import com.alibaba.cloud.domain.dto.BankTransferDto;
import com.alibaba.cloud.domain.entity.BankTransfer;
import com.alibaba.cloud.infrastructure.repository.BankTransferRepository;
import lombok.extern.slf4j.Slf4j;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.stereotype.Controller;

import java.util.UUID;

@Controller
@Slf4j
public class BankTransferController {

	private final CommandGateway commandGateway;
	private final BankTransferRepository bankTransferRepository;

	public BankTransferController(CommandGateway commandGateway, BankTransferRepository bankTransferRepository) {
		this.commandGateway = commandGateway;
		this.bankTransferRepository = bankTransferRepository;
	}

	@SubscribeMapping("/bank-accounts/{bankAccountId}/bank-transfers")
	public Iterable<BankTransfer> bankTransfers(@DestinationVariable String bankAccountId) {
		log.info("Retrieve bank transfers for bank account with id {}", bankAccountId);
		return bankTransferRepository.findBySourceBankAccountIdOrDestinationBankAccountId(bankAccountId, bankAccountId);
	}

	@MessageMapping("/bank-transfers/{id}")
	public BankTransfer get(@DestinationVariable Long id) {
		log.info("Retrieve bank transfer with id {}", id);
		return bankTransferRepository.findById(id).get();
	}

	/****
	 * @description: 申请转账
	 * @author: zhuhb
	 * @date: 2022/8/23 15:36
	 */
	@MessageMapping("/bank-transfers/create")
	public void create(BankTransferDto bankTransferDto) {
		log.info("Create bank transfer with payload {}", bankTransferDto);
		String bankTransferId = UUID.randomUUID().toString();
		CreateBankTransferCommand command = new CreateBankTransferCommand(bankTransferId,
				bankTransferDto.getSourceBankAccountId(), bankTransferDto.getDestinationBankAccountId(),
				bankTransferDto.getAmount());
		commandGateway.send(command);
	}
}
